import { useLocation } from '@umijs/max';
import { useState } from 'react';

export const getObjFromSearchUrl = (search: string) => {
  const urlStringParams = search?.includes('?')
    ? search?.replace('?', '')
    : search;

  const paramsArr =
    urlStringParams?.length > 0
      ? urlStringParams?.split('&')?.map((item: string) => {
          const [key, value] = item?.split('=');
          return {
            [key]: value,
          };
        })
      : [];

  const currUrlParams = paramsArr?.reduce((sum: any, cur: any) => {
    return { ...sum, ...cur };
  }, {});
  return currUrlParams;
};

const useSetSearchParams = () => {
  const location = useLocation();
  const { search } = location;
  const [currUrlParams, setCurrUrlParams] = useState(
    getObjFromSearchUrl(search),
  );
  const setUrlParams = (callFn: (params: any) => void) => {
    const newParams: any = callFn(currUrlParams);
    if (typeof newParams === 'object' && Object.keys(newParams).length > 0) {
      const newUrlParams = new URLSearchParams(newParams);
      setCurrUrlParams(newParams);
      window.history.replaceState(null, '', `?${newUrlParams}`);
    } else {
      const url = new URL(window.location.href);
      setCurrUrlParams({});
      window.history.replaceState(null, '', url.origin + url.pathname);
    }
  };
  return {
    currUrlParams,
    setUrlParams,
  };
};

export default useSetSearchParams;
